package com.pg.excel.ui;

import com.pg.excel.ReadExcel;
import com.pg.excel.WriteExcel;
import com.pg.excel.bean.DidBean;
import com.pg.excel.util.PropertiesUtils;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Main {
    private JPanel panel;
    private JLabel failLabel;
    private JLabel successLabel;
    private MyButton successButton;
    private MyButton failButton;
    private MyButton startButton;
    private JTextField successPath;
    private JTextField failPath;
    private JLabel messageLabel;

    private Color bg1 = new Color(69, 73, 74);
    private Color bg2 = new Color(60, 63, 65);
    private Color border = new Color(120, 120, 120);
    private FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel 工作簿(*.xlsx)", "xlsx");
    private FileNameExtensionFilter csvFilter = new FileNameExtensionFilter("CSV (*.csv)", "csv");

    private Main() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ignored) { }
        successButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                successPath.setText(fileChooser());
            }


        });
        failButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                failPath.setText(fileChooser());
            }
        });
        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                startExcel();
            }
        });
    }

    private void startExcel(){

        final String sPath = successPath.getText().trim();
        final String fPath = failPath.getText().trim();
        if (showMessageDialog(sPath)) return;
        if (showMessageDialog(fPath)) return;
        startButton.setEnabled(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                messageLabel.setText("开始读取第一份文件");
                List<DidBean> success = ReadExcel.getInstance().readExcelDids(sPath);
                messageLabel.setText("开始读取第二份文件");
                List<DidBean> fails = ReadExcel.getInstance().readExcelDids(fPath);
                messageLabel.setText("开始处理数据");
                List<DidBean> result = new ArrayList<DidBean>();
                List<DidBean> temp = new ArrayList<DidBean>();
                for (DidBean bean : success){
                    bean.setSuccess(bean.getNumber());
                    for (DidBean fBean : fails){
                        if (bean.getDid().equalsIgnoreCase(fBean.getDid())){
                            bean.setFail(fBean.getNumber());
                            temp.add(fBean);
                            break;
                        }
                    }
                    result.add(bean);
                }
                fails.removeAll(temp);
                for (DidBean fBean : fails){
                    fBean.setFail(fBean.getNumber());
                    fBean.setSuccess(0);
                    result.add(fBean);
                }
                messageLabel.setText("开始生成Excel文件");
                String outPath = new File(sPath).getParent()+File.separator+"result-"+System.currentTimeMillis()+".xlsx";
                WriteExcel.getInstance().writeExcelDids(result,outPath);
                messageLabel.setText("完成");
                startButton.setEnabled(true);
            }
        }).start();
    }

    private boolean showMessageDialog(String path) {
        if (path.length() < 1) {
            JOptionPane.showMessageDialog(panel, "请选择Excel", "没选文件", JOptionPane.WARNING_MESSAGE);
            return true;
        }
        File sFile = new File(path);
        if (!sFile.exists()) {
            JOptionPane.showMessageDialog(panel, "请选择正确Excel", "文件不存在", JOptionPane.WARNING_MESSAGE);
            return true;
        }
        return false;
    }

    private String fileChooser() {
        JFileChooser fd = new JFileChooser();
        String inputPath = PropertiesUtils.getInstance().getLastPath();
        if (inputPath.length() > 1) {
            try {
                File inputFile = new File(inputPath);
                fd.setCurrentDirectory(inputFile);
            } catch (Exception ignored) { }
        }
        fd.setFileSelectionMode(JFileChooser.FILES_ONLY);
        //文件类型 里是否显示 所有文件 默认true
        fd.setAcceptAllFileFilterUsed(false);
        fd.addChoosableFileFilter(filter);
        fd.addChoosableFileFilter(csvFilter);
        fd.setFileFilter(csvFilter);
        int result = fd.showOpenDialog(panel);
        if (result == JFileChooser.APPROVE_OPTION) {
            File f = fd.getSelectedFile();
            if (f != null) {
                System.out.println("选择的过滤器:"+fd.getFileFilter());
                String inPath = f.getAbsolutePath();
                System.out.println("选择的文件夹:"+inPath);
                PropertiesUtils.getInstance().setProperties(inPath);
                return inPath;
            }
        }
        return"";
    }

    public static void main(String[]args){
        JFrame frame = new JFrame("xx 1.0");
        frame.setResizable(false);
        Toolkit tool = frame.getToolkit();
        try {
            Image image = tool.getImage(frame.getClass().getResource("/img/icon.png"));
            frame.setIconImage(image);
        }catch (Exception e){
            e.printStackTrace();
        }
        Main m = new Main();
        m.createUiComponents();
//        m.setWindow(frame);
        frame.setContentPane(m.panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setSize(647, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void createUiComponents() {
        panel.setLayout(null);
        panel.setBackground(bg2);

        messageLabel.setBounds(40,40,567,40);
//        messageLabel.setBorder(new TextBorderUtlis(border, 1, true));

        successLabel.setBounds(40,100,150,40);
//        successLabel.setBorder(new TextBorderUtlis(border, 1, true));
        successPath.setBounds(200,100,287,40);
        successPath.setBorder(new TextBorderUtlis(border, 1, true));
        successPath.setBackground(bg1);
        successButton.setBounds(497,100,110,40);

        failLabel.setBounds(40,160,150,40);
//        successLabel.setBorder(new TextBorderUtlis(border, 1, true));
        failPath.setBounds(200,160,287,40);
        failPath.setBorder(new TextBorderUtlis(border, 1, true));
        failPath.setBackground(bg1);
        failButton.setBounds(497,160,110,40);
        startButton.setBounds(243,220,160,64);

    }

}
